package com.pang.springcloud.controller;


import com.pang.springcloud.entities.CommonResult;
import com.pang.springcloud.entities.Payment;
import com.pang.springcloud.lib.MyLoadBalancer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * @author： pang-yun
 * @date： 2022-02-08 15:16
 * Description:
 */
@RestController
public class OrderController {

    //写死 单机服务
//    public static final String PAYMENT_URL = "http://localhost:8001";

    // 多个服务提供者
    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/consumer/payment/add")
    public CommonResult<Payment> add(Payment payment) {
        return restTemplate.postForObject(PAYMENT_URL + "/payment/add", payment, CommonResult.class);

    }

    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id") Long id) {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
    }


    /*
     * restTemplate。getForObject 返回对象为响应体数据转化的对象， 基本上可以理解为Json
     * restTemplate.getForEntity  返回对象为ResponseEntity 包含了相应中的一下重要信息 比武 响应头、响应码、响应体等
     * */
    @GetMapping("/consumer/payment/entity/{id}")
    public CommonResult<Payment> getPaymentByEntity(@PathVariable("id") Long id) {
        ResponseEntity<CommonResult> forEntity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
        if (forEntity.getStatusCode().is2xxSuccessful()) {
            return forEntity.getBody();
        } else {
            return new CommonResult<>(444, "操作失败");
        }
    }

    //-----------------------------自己手动编写负载均衡策略-------------------

    @Resource
    private DiscoveryClient discoveryClient;

    @Autowired
    private MyLoadBalancer loadBalancer;

    @GetMapping("/consumer/payment/loadBalances")
    public String getPaymentLoadBalances() {

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (instances == null || instances.size() <= 0) {
            return null;
        }
        ServiceInstance instance = loadBalancer.instances(instances);
        URI uri = instance.getUri();
        return restTemplate.getForObject(uri + "/payment/loadBalances", String.class);
    }



}
